package com.example.treasure_back.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.treasure_back.entity.AIResultEntity;
import com.example.treasure_back.entity.BusinessException;
import com.example.treasure_back.entity.MsgEntity;
import com.example.treasure_back.enumerate.CommentType;
import com.example.treasure_back.service.PictureService;
import com.example.treasure_back.service.TrashDataService;
import com.example.treasure_back.shiroEntity.auth.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

@RestController
@RequestMapping("/treasure/picture")
public class PictureController {

    @Autowired
    private PictureService pictureService;
    @Autowired
    private TrashDataService trashDataService;
    private final static String[] allowFileType = new String[]{".bmp", ".jpg", ".jpeg", ".png", ".gif"};

    @PostMapping("/upload")
    public MsgEntity uploadImage(@RequestParam("file") MultipartFile file, @AuthUser String email) throws IOException{
        if (file.isEmpty()){
            throw new BusinessException("-1","上传图片为空");
        }
        else{
            if (!Objects.requireNonNull(file.getOriginalFilename()).contains(".")){
                throw new BusinessException("-1", "文件解析异常");
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (suffix.isEmpty()|| !Arrays.asList(allowFileType).contains(suffix)){
                throw new BusinessException("-1", "文件格式错误");
            }
            //上传到oss
            AIResultEntity result = pictureService.uploadImage(file.getInputStream(), suffix, email);
            return new MsgEntity("SUCEESS","200",result);
        }
    }

    @PostMapping("/comment")
    public MsgEntity comment(@RequestBody JSONObject jsonObject){
        String image = jsonObject.getString("image");
        CommentType comment = CommentType.valueOf(jsonObject.getString("comment"));
        trashDataService.commentResult(image, comment);
        return new MsgEntity("SUCCESS", "200", "感谢您的反馈");
    }


}
